package com.toptower.rfid_read_write.view;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.gg.reader.api.dal.GClient;
import com.gg.reader.api.dal.HandlerGpiOver;
import com.gg.reader.api.dal.HandlerGpiStart;
import com.gg.reader.api.dal.HandlerTag6bLog;
import com.gg.reader.api.dal.HandlerTag6bOver;
import com.gg.reader.api.dal.HandlerTagEpcLog;
import com.gg.reader.api.dal.HandlerTagEpcOver;
import com.gg.reader.api.protocol.gx.EnumG;
import com.gg.reader.api.protocol.gx.LogAppGpiOver;
import com.gg.reader.api.protocol.gx.LogAppGpiStart;
import com.gg.reader.api.protocol.gx.LogBase6bInfo;
import com.gg.reader.api.protocol.gx.LogBase6bOver;
import com.gg.reader.api.protocol.gx.LogBaseEpcInfo;
import com.gg.reader.api.protocol.gx.LogBaseEpcOver;
import com.gg.reader.api.protocol.gx.MsgBaseInventory6b;
import com.gg.reader.api.protocol.gx.MsgBaseInventoryEpc;
import com.gg.reader.api.protocol.gx.MsgBaseStop;
import com.gg.reader.api.protocol.gx.ParamEpcReadTid;
import com.toptower.rfid_read_write.R;
import com.toptower.rfid_read_write.adapter.RecycleViewAdapter;
import com.toptower.rfid_read_write.entity.TagInfo;
import com.toptower.rfid_read_write.model.SingleBaseConfig;
import com.toptower.rfid_read_write.util.GlobalClient;
import com.toptower.rfid_read_write.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ReadOrWriteActivity extends AppCompatActivity {
    Button read,clean,stop;
    TextView row_index,row_tagcount,row_time,row_speed;
    private RecycleViewAdapter adapter;
    private GClient client = GlobalClient.getClient();
    private boolean isClient = false;
    private boolean isReader = false;
    private List<TagInfo> tagInfoList = new ArrayList<TagInfo>();//适配器所需数据源

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_or_write);
        initview();

        initRecycleView();


    }



    private void initview(){

        row_index=findViewById(R.id.row_index);
        row_speed=findViewById(R.id.row_speed);
        row_tagcount=findViewById(R.id.row_tagcount);
        row_time=findViewById(R.id.row_time);
        read=findViewById(R.id.read);
        stop=findViewById(R.id.stop);
        clean=findViewById(R.id.clean);

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readCard();
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopRead();
            }
        });

        clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cleanData();
            }
        });

     }

    public void initRecycleView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerView rv = (RecyclerView) findViewById(R.id.recycle);
        rv.setLayoutManager(layoutManager);
        rv.addItemDecoration(new DividerItemDecoration(this, 1));
        adapter = new RecycleViewAdapter(tagInfoList);
        rv.setAdapter(adapter);
    }

    //订阅
    public void subHandler(GClient client) {
        client.onTagEpcLog = new HandlerTagEpcLog() {
            public void log(String readerName, LogBaseEpcInfo info) {
                if (null != info && 0 == info.getResult()) {
//                    System.out.println(info);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Map<String, TagInfo> infoMap = pooled6cData(info);
                            tagInfoList.clear();
                            tagInfoList.addAll(infoMap.values());

                        }
                    });
                }
            }
        };
        client.onTagEpcOver = new HandlerTagEpcOver() {
            public void log(String readerName, LogBaseEpcOver info) {
                handlerStop.sendEmptyMessage(1);
            }
        };
        client.onTag6bLog = new HandlerTag6bLog() {
            public void log(String readerName, LogBase6bInfo info) {
//                System.out.println(info);
                //带上userData一起读则返回result与userData
                if (null != info) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Map<String, TagInfo> infoMap = pooled6bData(info);
                            tagInfoList.clear();
                            tagInfoList.addAll(infoMap.values());
                        }
                    });
                }
            }
        };
        client.onTag6bOver = new HandlerTag6bOver() {
            public void log(String readerName, LogBase6bOver info) {
                handlerStop.sendEmptyMessage(1);
            }
        };
        client.onGpiOver = new HandlerGpiOver() {
            @Override
            public void log(String s, LogAppGpiOver logAppGpiOver) {
                System.out.println(logAppGpiOver);
            }
        };
        client.onGpiStart = new HandlerGpiStart() {
            @Override
            public void log(String s, LogAppGpiStart logAppGpiStart) {
                System.out.println(logAppGpiStart);
            }
        };
    }


    public void readCard() {
        if (isClient) {
            if (!isReader) {
                if (SingleBaseConfig.getBaseConfig().getCardType().equals("6C")) {
                    MsgBaseInventoryEpc msg = new MsgBaseInventoryEpc();
                    msg.setAntennaEnable((long) getAnt());
                    if (way.getCheckedRadioButtonId() == R.id.single) {
                        msg.setInventoryMode(EnumG.InventoryMode_Single);
                    } else {
                        msg.setInventoryMode(EnumG.InventoryMode_Inventory);
                    }
                    if (isChecked[0]) {
                        tidParam = new ParamEpcReadTid();
                        tidParam.setMode(EnumG.ParamTidMode_Auto);
                        tidParam.setLen(6);
                        msg.setReadTid(tidParam);
                    } else {
                        tidParam = null;
                    }

                    client.sendSynMsg(msg);
                    initPane();
                    computedSpeed();
                    if (0x00 == msg.getRtCode()) {
                        ToastUtils.showText("开始读卡");
                        isReader = true;
                        System.out.println("MsgBaseInventoryEpc[OK].");
                    }
                } else {
                    MsgBaseInventory6b msg = new MsgBaseInventory6b();
                    msg.setAntennaEnable((long) getAnt());
                    if (way.getCheckedRadioButtonId() == R.id.single) {
                        msg.setInventoryMode(EnumG.InventoryMode_Single);
                    } else {
                        msg.setInventoryMode(EnumG.InventoryMode_Inventory);
                    }
                    msg.setArea(EnumG.ReadMode6b_Tid);
                    client.sendSynMsg(msg);
                    initPane();
                    computedSpeed();
                    if (0x00 == msg.getRtCode()) {
                        isReader = true;
                        System.out.println("MsgBaseInventory6B[OK].");
                    }
                }
            } else {
                ToastUtils.showText("请先停止读卡");
            }
        } else {
            ToastUtils.showText("未连接");
        }
    }


    //停止

    public void stopRead() {
        if (isClient) {
            MsgBaseStop msgStop = new MsgBaseStop();
            client.sendSynMsg(msgStop);
            if (0x00 == msgStop.getRtCode()) {
//                System.out.println("success.");
                isReader = false;
                ToastUtils.showText("停止成功");
            } else {
//                System.out.println("failure.");
                ToastUtils.showText("停止失败");
            }
        } else {
            ToastUtils.showText("未连接");
        }
    }

    //清屏

    public void cleanData() {
        if (isClient) {
            initPane();
        } else {
            ToastUtils.showText("未连接");
        }
    }


    //去重6B
    public Map<String, TagInfo> pooled6bData(LogBase6bInfo info) {
        if (tagInfoMap.containsKey(info.getTid())) {
            TagInfo tagInfo = tagInfoMap.get(info.getTid());
            Long count = tagInfoMap.get(info.getTid()).getCount();
            count++;
            tagInfo.setRssi(info.getRssi() + "");
            tagInfo.setCount(count);
            tagInfoMap.put(info.getTid(), tagInfo);
        } else {
            TagInfo tag = new TagInfo();
            tag.setIndex(index);
            tag.setType("6B");
            tag.setCount(1l);
            if (info.getTid() != null) {
                tag.setTid(info.getTid());
            }
            tag.setRssi(info.getRssi() + "");
            tagInfoMap.put(info.getTid(), tag);
            index++;
        }
        return tagInfoMap;
    }

}
